package com.newpage.module_lecture.adapter;

import android.content.Context;
import android.media.AudioManager;
import android.os.Build;
import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.recyclerview.widget.RecyclerView;

import com.jaygoo.widget.OnRangeChangedListener;
import com.jaygoo.widget.RangeSeekBar;
import com.newpage.module_lecture.R;
import com.wetao.lib_common.Constants;
import com.wetao.lib_common.bean.response.ExplainBean;
import com.wetao.lib_common.bean.response.QuestionExplainListInfo;
import com.wetao.lib_common.utils.ComUtil;
import com.wetao.lib_common.utils.LogUtils;
import com.wetao.lib_common.utils.StringUtil;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;

/**
 * author: zhouyh
 * created on: 2021/6/9 3:48 下午
 * description:
 */
public class QuestionExplainAdapter extends RecyclerView.Adapter<QuestionExplainAdapter.QuestionExplainViewHolder> {



    private Context mContext;
    private List<QuestionExplainListInfo.Data.RecordsBean> questionList = new ArrayList<>();
    private List<ExplainBean> explainListBeans = new ArrayList<>();

    private SparseBooleanArray audioMap = new SparseBooleanArray();
    private int audioSelectIndex = -1;
    private long curTime;
    private long mDuration = 0;
    private String audioTime ="00:00/00:00";
    private int curVolume;
    private float tempPosition;


    private int[] drawables = new int[]{
            R.drawable.common_understand,R.drawable.common_understand_enable,
            R.drawable.common_no_understand,R.drawable.common_no_understand_enable,
            R.drawable.understand_select,R.drawable.no_understand_select
    };
    private int[] colors = new int[]{
            R.color.understand_text_red,R.color.bar_color,
            R.color.understand_blue,R.color.understand_red,
            R.color.class_666666
    };


    public QuestionExplainAdapter(Context mContext) {
        this.mContext = mContext;
    }



    public void setExplainTeacherList(List<QuestionExplainListInfo.Data.RecordsBean> mData) {
        if (mData!=null){
            questionList.clear();
            questionList.addAll(mData);

            explainListBeans.clear();

            for (int i = 0; i < questionList.size();i++){
                explainListBeans.add(questionList.get(i).getExplainList().size()>0 ?
                        questionList.get(i).getExplainList().get(0):null);
            }
            notifyDataSetChanged();
        }

    }

    /**
     * 替换老师讲解
     * @param explainListBean
     * @param pos
     */
    public void setExplainTeacher(ExplainBean explainListBean, int pos) {
        if (explainListBean!=null){
            explainListBeans.set(pos,explainListBean);
            notifyDataSetChanged();
        }
    }

    @Override
    public int getItemViewType(int position) {
        return position;
    }

    @Override
    public int getItemCount() {
        return questionList.size();
    }

    @Override
    public long getItemId(int position) {
//        LogUtils.i("打印" + "===" + position);
        return position;
    }

    private OnItemClickListener onItemClickListener;


    /**
     * 更新音频时间
     * @param cur
     * @param duration
     */
    public void updateCurrentTime(long cur, long duration) { ;
        if (duration < 0 || cur == 0){
            audioTime = String.format("%s/%s", "00:00", ComUtil.strToTime(duration / 1000 + ""));
        }else {
            double temp = (double)cur / 1000;
            audioTime = String.format("%s/%s", ComUtil.strToTime("" + (int)(Math.round(temp))), ComUtil.strToTime(duration / 1000 + ""));
        }
        curTime = cur;
        mDuration = duration;

    }

    public void updateVolume(int currentVolume) {
        this.curVolume = currentVolume;
        notifyDataSetChanged();
    }

    public void musicCompletion() {
        updateCurrentTime(0,mDuration);
        audioMap.put(getAudioSelectIndex(),false);
        notifyDataSetChanged();
    }


    /**
     *息屏或onPause自定改变状态
     * @param isPlay
     */
    public void musicPause(boolean isPlay){
        if (!isPlay){
            audioMap.put(getAudioSelectIndex(),false);
        }
        notifyDataSetChanged();
    }

    /**
     * 重置时间
     */
    public void resetRangeSeek(int pos) {
        audioTime = String.format("%s/%s", "00:00", ComUtil.strToTime(explainListBeans.get(pos).getVideoTime() + ""));
        curTime = 0;
        notifyDataSetChanged();
    }


    public interface OnItemClickListener{
        void OnItemClickListener(int position);
        void onPopClick(View view, QuestionExplainListInfo.Data.RecordsBean bean,
                        int pos, ExplainBean explainListBean);
        void onVideoPlayClick(QuestionExplainListInfo.Data.RecordsBean recordsBean, ExplainBean explainBean);
        void onAudioPlayClick(String path,int pos);
        void onVoiceClick();
        void onUnderStandEventClick(Integer id,Integer isUnderstand);
        void onRangeSeekBarChange(int curPosition, int i);
        void onPathError(int i); //地址出错
    }

    public void setRecordItemClickListener(OnItemClickListener clickListener) {
        this.onItemClickListener = clickListener;
    }

    @NonNull
    @NotNull
    @Override
    public QuestionExplainViewHolder onCreateViewHolder(@NonNull @NotNull ViewGroup viewGroup, int i) {
        View root = LayoutInflater.from(mContext).inflate(R.layout.lecture_question_explain_item,viewGroup,false);
        return new QuestionExplainViewHolder(root);
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    public void onBindViewHolder(@NonNull @NotNull QuestionExplainViewHolder viewHolder, int i) {

        if (questionList!=null && questionList.size() > 0){
            viewHolder.tv_question_title.setText(
                    String.format("第%s题" + "（" + "%s" + ")",questionList.get(i).getSortNo(), StringUtil.replaceAmp(questionList.get(i).getExamName())));

            viewHolder.tv_question_time.setText(questionList.get(i).getCreateTime());
        }

        if (explainListBeans.size() > 0) {
            ExplainBean temp = explainListBeans.get(i);
            if (temp != null && temp.getExplainType() != null) {
                viewHolder.tv_teacher_name.setText(temp.getExplainName());
                if (temp.getExplainType() == Constants.TYPE_AUDIO) {
                    viewHolder.ll_audio.setVisibility(View.VISIBLE);
                    viewHolder.ll_video.setVisibility(View.GONE);
                } else if (temp.getExplainType() == Constants.TYPE_VIDEO) {
                    viewHolder.ll_audio.setVisibility(View.GONE);
                    viewHolder.ll_video.setVisibility(View.VISIBLE);
                    viewHolder.tv_video_play.setCompoundDrawablesWithIntrinsicBounds(R.drawable.common_video_mp4, 0, 0, 0);
                    viewHolder.tv_video_play.setText(ComUtil.stringForTime(temp.getVideoTime() * 1000));
                } else if (temp.getExplainType() == Constants.TYPE_TRACK) {
                    viewHolder.ll_audio.setVisibility(View.GONE);
                    viewHolder.ll_video.setVisibility(View.VISIBLE);
                    viewHolder.tv_video_play.setCompoundDrawablesWithIntrinsicBounds(R.drawable.common_video_track, 0, 0, 0);
                    viewHolder.tv_video_play.setText(ComUtil.stringForTime(temp.getVideoTime() * 1000));
                }
            }


            viewHolder.ll_pop_teacher.setOnClickListener(v -> {
                if (onItemClickListener != null) {
                    onItemClickListener.onPopClick(viewHolder.ll_pop_teacher, questionList.get(i), i, explainListBeans.get(i));
                }
            });

            viewHolder.tv_video_play.setOnClickListener(v -> {
                if (onItemClickListener != null) {
                    onItemClickListener.onVideoPlayClick(questionList.get(i), explainListBeans.get(i));
                }
            });

            viewHolder.iv_audio_play_or_pause.setOnClickListener(v -> {
                String path = explainListBeans.get(i).getExplainUrl();
                if (path == null || !path.endsWith(Constants.VIDEO_FORMAT)) {
                    if (onItemClickListener != null) {
                        onItemClickListener.onPathError(i);
                    }
                    return;
                } else {
                    if (onItemClickListener != null) {
                        onItemClickListener.onAudioPlayClick(path, i);
                    }
                }

                //选中与当前点击不一致，之前选中设为false
                if (getAudioSelectIndex() != i) {
                    audioMap.put(getAudioSelectIndex(), false);
                }
                if (audioMap.get(i)) {
                    audioMap.put(i, false);
                } else {
                    audioMap.put(i, true);
                }
                LogUtils.e("musicPause:" + "click audioMap =" + audioMap.get(i) + ",index ==" + i);
                setAudioSelectIndex(i);
                notifyDataSetChanged();
            });

            if (audioMap.get(i)) {
                viewHolder.iv_audio_play_or_pause.setImageResource(R.drawable.common_video_pause);
            } else {
                viewHolder.iv_audio_play_or_pause.setImageResource(R.drawable.common_video_start);
            }


            /**
             * 声音事件
             */
            viewHolder.iv_voice_open_or_close.setOnClickListener(v -> {
                if (onItemClickListener != null) {
                    onItemClickListener.onVoiceClick();
                }
            });

            if (curVolume == 0) {
                viewHolder.iv_voice_open_or_close.setImageResource(R.drawable.common_voice_close);
            } else {
                viewHolder.iv_voice_open_or_close.setImageResource(R.drawable.common_voice);
            }

            /**
             * 音频进度条
             */
            if (getAudioSelectIndex() == i) {
                viewHolder.tv_audio_time.setText(audioTime);
                float progress = curTime * viewHolder.rsb.getMaxProgress() / mDuration;
                if (explainListBeans.get(i).getVideoTime()!=null && explainListBeans.get(i).getVideoTime()==0){
                    explainListBeans.get(i).setVideoTime((int) (mDuration / 1000));
                }
                viewHolder.rsb.setProgress(progress < 0 ? 0 : progress);
            } else {
                if (explainListBeans.get(i) != null && explainListBeans.get(i).getVideoTime() != null) {
                    viewHolder.tv_audio_time.setText(String.format("%s/%s", "00:00", ComUtil.strToTime(explainListBeans.get(i).getVideoTime() + "")));
                } else {
                    viewHolder.tv_audio_time.setText(String.format("%s/%s", "00:00", "00:00"));
                }
                viewHolder.rsb.setProgress(0);
            }


            viewHolder.rsb.setOnRangeChangedListener(new OnRangeChangedListener() {
                @Override
                public void onRangeChanged(RangeSeekBar view, float leftValue, float rightValue, boolean isFromUser) {
                    if (isFromUser) {
                        LogUtils.i("rsb_audio_progress: onRangeChanged -- leftValue = " + leftValue + ", rightValue = " + rightValue + ", isFromUser = " + isFromUser);
                        tempPosition = leftValue;
                    }
                }

                @Override
                public void onStartTrackingTouch(RangeSeekBar view, boolean isLeft) {

                }

                @Override
                public void onStopTrackingTouch(RangeSeekBar view, boolean isLeft) {
                    int cur = (int) (tempPosition / view.getMaxProgress() * mDuration);
                    LogUtils.i("rsb_audio_progress: onRangeChanged -- leftValue = "
                            + tempPosition + ", maxProgress = " + view.getMaxProgress() + ", duration = " + explainListBeans.get(i).getVideoTime());
                    if (onItemClickListener != null) {
                        onItemClickListener.onRangeSeekBarChange(cur, i);
                    }
                }
            });


            if (questionList.get(i).getIsUnderstand() == null) {
                //默认未选择
                viewHolder.ll_understand.setBackground(mContext.getResources().getDrawable(drawables[4]));
                viewHolder.ll_no_understand.setBackground(mContext.getResources().getDrawable(drawables[5]));
                viewHolder.tv_understand.setTextColor(mContext.getResources().getColor(colors[4]));
                viewHolder.tv_no_understand.setTextColor(mContext.getResources().getColor(colors[4]));
                viewHolder.iv_understand.setImageResource(drawables[0]);
                viewHolder.iv_no_understand.setImageResource(drawables[2]);
            } else if (questionList.get(i).getIsUnderstand() == 0) {
                //未懂
                viewHolder.ll_understand.setBackground(mContext.getResources().getDrawable(drawables[4]));
                viewHolder.ll_no_understand.setBackground(mContext.getResources().getDrawable(drawables[5]));
                viewHolder.tv_understand.setTextColor(mContext.getResources().getColor(colors[4]));
                viewHolder.tv_no_understand.setTextColor(mContext.getResources().getColor(colors[0]));
                viewHolder.iv_no_understand.setImageResource(drawables[3]);
                viewHolder.iv_understand.setImageResource(drawables[0]);
            } else if (questionList.get(i).getIsUnderstand() == 1) {
                //已懂
                viewHolder.ll_understand.setBackground(mContext.getResources().getDrawable(drawables[4]));
                viewHolder.ll_no_understand.setBackground(mContext.getResources().getDrawable(drawables[5]));
                viewHolder.tv_understand.setTextColor(mContext.getResources().getColor(colors[1]));
                viewHolder.tv_no_understand.setTextColor(mContext.getResources().getColor(colors[4]));
                viewHolder.iv_understand.setImageResource(drawables[1]);
                viewHolder.iv_no_understand.setImageResource(drawables[2]);
            }

            viewHolder.ll_understand.setOnClickListener(v -> {
                questionList.get(i).setIsUnderstand(1);
                viewHolder.ll_understand.setSelected(true);
                viewHolder.iv_understand.setSelected(true);
                viewHolder.ll_no_understand.setSelected(false);
                viewHolder.iv_no_understand.setSelected(false);
                if (onItemClickListener != null) {
                    onItemClickListener.onUnderStandEventClick(questionList.get(i).getId(), 1);

                }
            });


            viewHolder.ll_no_understand.setOnClickListener(v -> {
                questionList.get(i).setIsUnderstand(0);
                viewHolder.ll_understand.setSelected(false);
                viewHolder.iv_understand.setSelected(false);
                viewHolder.ll_no_understand.setSelected(true);
                viewHolder.iv_no_understand.setSelected(true);

                if (onItemClickListener != null) {
                    onItemClickListener.onUnderStandEventClick(questionList.get(i).getId(), 0);
                }
            });
        }

    }

    public int getAudioSelectIndex() {
        return audioSelectIndex;
    }

    public void setAudioSelectIndex(int audioSelectIndex) {
        this.audioSelectIndex = audioSelectIndex;
    }

    class QuestionExplainViewHolder extends RecyclerView.ViewHolder{

        private LinearLayout ll_pop_teacher;
        private LinearLayout ll_video;
        private LinearLayout ll_audio;
        private TextView tv_audio_time;
        private TextView tv_question_title;
        private TextView tv_question_time;
        private TextView tv_teacher_name;
        private TextView tv_video_play;
        private LinearLayout ll_understand;
        private ImageView iv_understand;
        private TextView tv_understand;
        private LinearLayout ll_no_understand;
        private ImageView iv_no_understand;
        private TextView tv_no_understand;
        private RangeSeekBar rsb;
        private ImageView iv_teacher_up_down;
        private ImageView iv_audio_play_or_pause;
        private ImageView iv_voice_open_or_close;

        public QuestionExplainViewHolder(@NonNull View itemView) {
            super(itemView);
            ll_pop_teacher = itemView.findViewById(R.id.ll_pop_teacher);
            ll_video = itemView.findViewById(R.id.ll_video);
            ll_audio = itemView.findViewById(R.id.ll_audio);
            tv_question_title = itemView.findViewById(R.id.tv_question_title);
            tv_question_time = itemView.findViewById(R.id.tv_question_time);
            tv_teacher_name = itemView.findViewById(R.id.tv_pop_teacher_name);
            tv_video_play = itemView.findViewById(R.id.tv_video);
            ll_understand = itemView.findViewById(R.id.ll_understand);
            iv_understand = itemView.findViewById(R.id.iv_understand);
            tv_understand = itemView.findViewById(R.id.tv_understand);
            ll_no_understand = itemView.findViewById(R.id.ll_no_understand);
            iv_no_understand = itemView.findViewById(R.id.iv_no_understand);
            tv_no_understand = itemView.findViewById(R.id.tv_no_understand);
            rsb = itemView.findViewById(R.id.rsb_audio_progress);
            iv_teacher_up_down = itemView.findViewById(R.id.iv_popDowUp_teacher);
            iv_audio_play_or_pause = itemView.findViewById(R.id.iv_audio_play_or_pause);
            iv_voice_open_or_close = itemView.findViewById(R.id.iv_voice_play_or_pause);
            tv_audio_time = itemView.findViewById(R.id.tv_audio_time);
        }
    }



}
